package com.itheima.api;

import com.itheima.domain.Video;
import com.itheima.util.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.annotation.Resource;
import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi{

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private IdWorker idWorker;

    /**
     * 保存视频
     * @param video
     * @return
     */
    @Override
    public String save(Video video) {
        video.setVid(idWorker.getNextId("video"));
        Video save = mongoTemplate.save(video);
        return save.getId().toHexString();
    }

    /**
     * 根据pids查视频
     * @param pids
     * @return
     */
    @Override
    public List<Video> getVideo(List<Long> pids) {
        Query query = Query.query(Criteria.where("vid").in(pids));
        return mongoTemplate.find(query,Video.class);
    }

    /**
     * 分页查询
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> getByPage(int page, Integer pagesize) {
        Query query = new Query().limit(pagesize).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

}
